package com.cjf.aop.runtime.utils;

import android.util.SparseArray;
import android.view.View;

import com.cjf.aop.annotation.SingleClick;

/**
 * 快速点击工具类
 * created by cjf
 * on: 2020/3/23
 */
public class ClickUtils {
    /**
     * 最近一次点击的时间
     */
    private static long sLastClickTime = 0;
    /**
     * 最近一次点击的控件ID
     */
    private static int sLastClickViewId;
    /**
     * key 控件ID  value 最近一次点击的时间
     */
    private volatile static SparseArray<Long> sLastClickArray;

    private static SparseArray<Long> getsLastClickArray() {
        if (sLastClickArray == null) {
            synchronized (ClickUtils.class) {
                if (sLastClickArray == null) {
                    sLastClickArray = new SparseArray<>();
                }
            }
        }
        return sLastClickArray;
    }

    /**
     * Don't let anyone instantiate this class.
     */
    private ClickUtils() {
        throw new UnsupportedOperationException("Do not need instantiate!");
    }

    /**
     * 是否是快速点击
     *
     * @param v 点击的控件
     * @return true:是，false:不是
     */
    public static boolean isFastDoubleClick(View v) {
        return isFastDoubleClick(v, SingleClick.DEFAULT_INTERVAL_MILLIS, false);
    }

    /**
     * 是否是快速点击
     *
     * @param v              点击的控件
     * @param intervalMillis 时间间期（毫秒）
     * @param isAllControl   是否所有控件共享连续点击
     * @return true:是，false:不是
     */
    public static boolean isFastDoubleClick(View v, long intervalMillis, boolean isAllControl) {
        long time = System.currentTimeMillis();
        int viewId = v.getId();

        if (isAllControl) {
            long duration = time - sLastClickTime;
            if (duration < intervalMillis) {
                return true;
            }
            sLastClickTime = time;
            sLastClickViewId = viewId;
        } else {
            SparseArray<Long> array = getsLastClickArray();
            long lastTime = array.get(viewId, -1L);
            if (lastTime != -1L) {
                long duration = time - lastTime;
                if (duration < intervalMillis) {
                    return true;
                }
            }
            array.put(viewId, time);
        }
        return false;
    }
}
